<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="单据时间" prop="workstationName">
        <el-select v-model="queryParams.lastDays" placeholder="请选择单据时间">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购单据编号" prop="poCode">
        <el-input
          v-model="queryParams.poCode"
          placeholder="请输入采购单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商简称" prop="vendorNick">
        <el-input
          v-model="queryParams.vendorNick"
          placeholder="请输入供应商简称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item >
        <el-radio-group v-model="queryParams.poStatusList">
          <el-radio :label="'not_in'">从未交货</el-radio>
          <el-radio :label="'part_in'">部分交货</el-radio>
          <el-radio :label="'all_in'">完全交货</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item >
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="getList"
        >搜索</el-button>

        <el-button
          type="default"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete(false)"
        >删除</el-button>
      </el-col>
    </el-row>

    <vxe-table
      border
      stripe
      ref="tableRef"
      size="small"
      header-align="center"
      :row-config="rowConfig"
      :column-config="columnConfig"
      @checkbox-change="checkboxChangeEvent"
      @checkbox-all="checkboxAll"
      @cell-click="cellClickEvent"
      :data="tableData"
      height="520"
    >
      <vxe-column type="checkbox" width="40" fixed="left"></vxe-column>
      <vxe-column field="rtCode" width="200" show-overflow="title" align="center" title="退货单据编号" drag-sort></vxe-column>
      <vxe-column field="poCode" width="200" show-overflow="title" align="center" title="采购单据编号"></vxe-column>
      <vxe-column field="age" width="120" show-overflow="title" align="center" title="退回仓库"></vxe-column>
      <vxe-column field="vendorCode" width="180" show-overflow="title" align="center" title="供应商代码"></vxe-column>
      <vxe-column field="vendorNick" width="180" show-overflow="title" align="center" title="供应商简称"></vxe-column>
      <vxe-column field="principal" width="180" show-overflow="title" align="center" title="供应商负责人"></vxe-column>
      <vxe-column field="contact" width="180" show-overflow="title" align="center" title="供应商联络人"></vxe-column>
      <vxe-column field="purchaser" width="180" show-overflow="title" align="center" title="采购员"></vxe-column>
      <vxe-column width="120" show-overflow="title" align="center" title="制单日期">
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime,'{y}-{m}-{d}') }}</span>
        </template>
      </vxe-column>
      <vxe-column field="rtDate" width="160" show-overflow="title" align="center" title="退货日期"></vxe-column>
      <vxe-column field="quantityRted" width="120" show-overflow="title" align="center" title="数量合计"></vxe-column>
      <vxe-column field="totalPrice" width="120" show-overflow="title" align="center" title="总价(含税)" ></vxe-column>
      <vxe-column field="totalPriceExTax" width="160" show-overflow="title" align="center" title="总价(不含税)" ></vxe-column>
      <vxe-column width="160" align="center" title="操作" fixed="right">
        <template #default="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
          >{{row.status =='PREPARE'?'修改':'查看'}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="row.status =='PREPARE'"
            @click="handleDelete(row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlePrint(row)"
          >打印</el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div class="app-container-footer">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick" :lazy="true">
        <el-tab-pane label="退货订单详情" name="1"><baseInfo :rtId="rtId" :poId="poId" :rtStatus="rtStatus" /></el-tab-pane>
        <el-tab-pane label="备注" name="2">备注</el-tab-pane>
      </el-tabs>
    </div>

    <!-- 添加或修改供应商退货对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="960px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货单编号" prop="rtCode">
              <el-input v-model="form.rtCode" :disabled="form.rtId?true:false" placeholder="请输入退货单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item  label-width="80">
              <el-switch 
                :disabled="form.rtCode != null"
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view' && form.status =='PREPARE'">               
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退货单名称" prop="rtName">
              <el-input v-model="form.rtName" placeholder="请输入退货单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购订单编号" prop="poCode" label-width="120px">
              <el-select v-model="form.poCode"  placeholder="请选择采购订单编号" clearable filterable @change="handlePoCodeChange">
                <el-option
                  v-for="dict in rtCodeOptions"
                  :key="dict.id"
                  :label="dict.poCode"
                  :value="dict.poCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商" >
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" v-if="showItemSelect" @closeSelect="closeSelect" @onSelected="onVendorSelected" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货日期" prop="rtDate">
              <el-date-picker clearable
                v-model="form.rtDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择退货日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" disabled placeholder="请选择单据状态">
                <el-option
                  v-for="dict in dict.type.mes_order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="币种名称" prop="currency">
              <el-select v-model="form.currency" placeholder="请选择币种">
                <el-option
                  v-for="dict in dict.type.currency_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="总价(含税)" prop="totalPrice">
              <el-input-number :min='0'  v-model="form.totalPrice"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价(不含税)" prop="totalPriceExTax">
              <el-input-number :min='0'  v-model="form.totalPriceExTax"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
             <el-divider content-position="center">物料信息</el-divider> 
       <el-card shadow="always" class="box-card">
         <div class="mb8">
           <el-button type="primary" size="small" @click="handleAddMaterial" v-if="optType != 'view'">+ 新增</el-button>
           <el-button type="danger" size="small" @click="handleDeleteMaterial" v-if="optType != 'view'">删除</el-button>
         </div>
         
         <el-table :data="materialList" @selection-change="handleMaterialSelectionChange" v-loading="materialLoading">
           <el-table-column type="selection" width="55" align="center" />
           <el-table-column label="物料编码" width="120" align="center" prop="itemCode" />
           <el-table-column label="物料名称" width="150" align="center" prop="itemName" :show-overflow-tooltip="true"/>
           <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
           <el-table-column label="单位" align="center" prop="unitOfMeasure" />
           <el-table-column label="退货数量" width="160" align="center" prop="quantityRted" v-if="optType != 'view'">
             <template slot-scope="scope">
               <el-input-number 
                 v-model="scope.row.quantityRted" 
                 :min="0" 
                 size="mini" 
                 @change="handleQuantityChange(scope.row)"
                 style="width: 160px"
               />
             </template>
           </el-table-column>
           <el-table-column width="180" label="单价(含税)" align="center" prop="price" v-if="optType != 'view'">
             <template slot-scope="scope">
               <el-input-number 
                 v-model="scope.row.price" 
                 :min="0" 
                 :precision="2"
                 size="mini" 
                 @change="handlePriceChange(scope.row)"
                 style="width: 160px"
               />
             </template>
           </el-table-column>
           <el-table-column label="单价(含税)" align="center"width="160" prop="price" v-else />
           <el-table-column label="总价(含税)" align="center" prop="totalPrice" />
           <el-table-column label="单价(不含税)" align="center" prop="priceExTax" />
           <el-table-column label="总价(不含税)" align="center" prop="totalPriceExTax" />
           <el-table-column label="可用库存数量" align="center" prop="availableStock" />
           <el-table-column label="外包装数量" align="center" prop="packageQuantity" />
           <el-table-column label="折扣(100%)" align="center" prop="discount" />
           <el-table-column label="税率" align="center" prop="taxRate" />
           <el-table-column width="100px" label="批次号" align="center" prop="batchCode" v-if="optType != 'view'">
             <template slot-scope="scope">
               <el-input 
                 v-model="scope.row.batchCode" 
                 size="mini" 
                 placeholder="请输入批次号"
                 style="width: 80px"
               />
             </template>
           </el-table-column>
           <el-table-column label="批次号" align="center" prop="batchCode" v-else />
           <el-table-column label="操作" width="100" align="center" v-if="optType != 'view'">
             <template slot-scope="scope">
               <el-button size="mini" type="text" @click="handleDeleteMaterial(scope.row)">删除</el-button>
             </template>
           </el-table-column>
         </el-table>
         
         <!-- 物料产品选择组件 -->
         <ItemSelect ref="itemSelect" v-if="showItemSelect" @closeSelect="closeItemSelect" @onSelected="onItemSelected"></ItemSelect>
       </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>
        <el-button type="primary" @click="submitForm1" v-if="form.id && form.status =='PREPARE' && optType !='view' ">提 交</el-button>        
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">确 定</el-button>        
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRtvendor, listPoRtvendor, getRtvendor, delRtvendor, addRtvendor, updateRtvendor, execute } from "@/api/mes/wm/rtvendor";
import { listRtvendorline, getRtvendorline, delRtvendorline, addRtvendorline, updateRtvendorline } from "@/api/mes/wm/rtvendorline";
import { listPurchaseOrder, getListConfirmed, detailPurchaseOrder } from "@/api/mes/pro/purchaseOrder";
import { listWarehouse } from "@/api/mes/wm/warehouse";
import {genCode} from "@/api/system/autocode/rule"
import baseInfo from "./components/baseInfo.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import Rtvendorline from "@/views/mes/wm/rtvendor/line.vue"
import ItemSelect from "@/components/itemSelect/multipleChoice.vue"
export default {
  name: 'purchaseReturns',
  components: { 
    baseInfo,
    VendorSelect,
    Rtvendorline,
    ItemSelect,
  },
  dicts: ['mes_order_status', 'currency_type'],
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lastDays: undefined,
        poCode: undefined,
        vendorNick: undefined,
        poStatusList: undefined,
        poCheckStatusList: undefined,
      },
      tableData: [],
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
      },
      total: 0,
      activeName: "1",
      rtId: undefined,
      poId: undefined, // 采购订单id
      baseInfoData: [], // 基础信息
      baseInfototal: 0,
      ids: [],
      options: [
        {
          value: '7',
          label: '7天'
        }, {
          value: '30',
          label: '30天'
        }, {
          value: '90',
          label: '90天'
        }, {
          value: '180',
          label: '180天'
        },
      ],
      //自动生成编码
      autoGenFlag:false,
      optType: undefined, //操作类型
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        rtCode: [
          { required: true, message: "退货单编号不能为空", trigger: "blur" }
        ],
        rtName: [
          { required: true, message: "退货单名称不能为空", trigger: "blur" }
        ],
        vendorName: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        rtDate: [
          { required: true, message: "退货日期不能为空", trigger: "blur" }
        ],
        poCode: [
          { required: false, message: "采购单编号不能为空", trigger: "change" }
        ]
      },
      rtCodeOptions: [], // 退货单编号list
      warehouseList: [], // 仓库list
      rtStatus: undefined, // 状态
      showItemSelect: false, // 是否显示物料选择
      materialList: [], // 物料列表
      materialLoading: false, // 物料加载状态
      selectedMaterialIds: [], // 选中的物料ID
      // 采购订单相关数据
      purchaseOrderData: [], // 采购订单列表数据
      purchaseOrderTotal: 0, // 采购订单总数
      purchaseOrderLoading: false, // 采购订单加载状态
    }
  },
  created() {
    this.getList();
    getListConfirmed({ pageNum: 1, pageSize: 9999 }).then(response => {
      this.rtCodeOptions = response.rows;
    })
    listWarehouse({ pageNum: 1, pageSize: 9999 }).then(response => {
      this.warehouseList = response.rows;
    })
  },
  methods: {
    getList(){
      // this.tableData = []
      this.queryParams.poStatusList = this.queryParams.poStatusList?[this.queryParams.poStatusList]:null
      this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?[this.queryParams.poCheckStatusList]:null
      listPoRtvendor(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.rtId = this.tableData[0].rtId;
        this.poId = this.tableData[0].poId;
        this.$nextTick(() => {
          this.$refs.tableRef.setCurrentRow(this.tableData[0]);
          this.cellClickEvent({row: this.tableData[0]})
        })
      }).finally(() => {
        this.queryParams.poStatusList = this.queryParams.poStatusList?.join()
        this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?.join()
      })
    },
    resetQuery(){
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        starTime: undefined,
        endTime: undefined,
        poCode: undefined,
        vendorName: undefined,
      }
      this.getList();
      console.log(123);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商退货";
      this.optType = "add";
      
      // 为新增操作创建一个临时的rtId，用于子组件显示
      this.form.rtId = 'temp_' + Date.now();
      
      // 新增后自动生成退货单编号,在这里进行填充新增的自动填充
      this.autoGenFlag = true;
      this.handleAutoGenChange(true);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
        this.form = {...row};
        this.open = true;
        this.title = "修改供应商退货";
        this.optType = "edit";
      // });
    },
    handleQuery(){
      console.log(666);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rtIds = row.rtId || this.ids;
      if(typeof row== 'boolean'){
        if(!rtIds.length) return this.$modal.msgWarning("请至少选择一条数据!");
      }
      this.$modal.confirm('是否确认删除？').then(function() {
        return delRtvendor(rtIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    checkboxChangeEvent(checked){
      this.ids = checked.records.map(item => item.rtId)
      console.log(checked.records, this.ids);
    },
    checkboxAll(checked){
      this.ids = checked.records.map(item => item.rtId)
      console.log(checked.records, this.ids)
    },
    handleEdit(row){
      console.log(row);
    },
    handleWithdrawPlan(row){
      console.log(row);
    },
    cellClickEvent({row}){
      this.rtId = row.rtId;
      this.poId = row.poId;
      this.rtStatus = row.status;
      this.handleClick({name:'1'})
      console.log(row);
    },
    handleClick(tab, event) {
      switch (tab.name) {
        case '1':
          console.log('基础信息');
          break;
        case '2':
          console.log('2');
          break;
        default:
          break;
      }
    },
    getBaseInfoList(
      params={
        pageNum: 1,
        pageSize: 10,
      } 
    ) {
      listRtvendorline({
        ...params,
        rtId: this.rtId,
      }).then(response => {
        this.baseInfoData = response.rows;
        this.baseInfototal = response.total;
      });
    },
    //供应商选择
    handleSelectVendor(){
      // 先显示组件，再设置showFlag
      this.showItemSelect = true;
      this.$nextTick(() => {
        if (this.$refs.vendorSelect) {
          this.$refs.vendorSelect.showFlag = true;
        }
      });
    },
    //供应商选择弹出框
    onVendorSelected(obj){
      if(obj != undefined && obj != null){
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        this.form.vendorNick = obj.vendorNick;
        // 清除供应商字段的验证错误
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate('vendorName');
          }
        });
        this.closeSelect();
      }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('WM_RTVENDOR_CODE').then(response =>{
          this.form.rtCode = response;
        });
      }else{
        this.form.rtCode = null;
      }
    },
    // 取消按钮
    cancel() {
      this.autoGenFlag = false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rtId: null,
        rtCode: null,
        rtName: null,
        poCode: null,
        poId: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        rtDate: new Date().toISOString().split('T')[0], // 使用 yyyy-MM-dd 格式
        status: "PREPARE",
        remark: null,
        discount: 1.0,
        totalPrice: 0,
        totalPriceExTax: 0,
        batchCode: "1",
        currency: "CNY",
        warehouseId: 217,
        warehouseName: "成品仓",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
      this.materialList = []; // 清空物料列表
      this.selectedMaterialIds = []; // 清空选中的物料ID
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.rtCodeOptions.forEach(item => {
            if(item.poCode == this.form.poCode){
              this.form.poId = item.id;
            }
          })
          
          // 获取物料列表数据,如果
          const rtVendorLines = this.materialList || [];
          
          // 确保物料列表不为空
          if (!rtVendorLines || rtVendorLines.length === 0) {
            this.$modal.msgError("请至少添加一条退货明细");
            return;
          }
          
          // 构造后端期望的数据结构
          const submitData = {
            rtVendor: this.cleanMainFormData({
              ...this.form,
              batchCode: this.form.batchCode || "1",
              currency: this.form.currency || "CNY",
              warehouseName: this.form.warehouseName || "成品仓"
            }),
            rtVendorLines: rtVendorLines
          };
          
          // 清理临时rtId
          if (this.form.rtId && this.form.rtId.toString().startsWith('temp_')) {
            delete submitData.rtVendor.rtId;
          }
        
          // 清理行数据中的临时ID，确保数据类型正确
          submitData.rtVendorLines = this.cleanTempIds(submitData.rtVendorLines);
          
          if (this.form.rtId != null && !this.form.rtId.toString().startsWith('temp_')) {
            updateRtvendor(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRtvendor(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handlePrint(row){
      console.log(row, window.location);
      window.open(window.location.origin + window.location.pathname + '#/printTemplate?rtId=' + row.rtId + '&type=out', '_blank');
    },
    submitForm1() {
      this.$confirm("提交之后不允许在修改，确定要修改吗？").then(() => {
        this.form.status = 'CONFIRMED'
        
        // 获取物料列表数据
        const rtVendorLines = this.materialList || [];
        
        // 确保物料列表不为空,如果没有则提示相关的消息
        if (!rtVendorLines || rtVendorLines.length === 0) {
          this.$modal.msgError("请至少添加一条退货明细");
          return;
        }
        
        // 构造后端期望的数据结构，根据后端期望的数据来进行数据的添加
        const submitData = {
          rtVendor: this.cleanMainFormData({
            ...this.form,
            batchCode: this.form.batchCode || "1",
            currency: this.form.currency || "CNY",
            warehouseName: this.form.warehouseName || "成品仓"
          }),
          rtVendorLines: rtVendorLines
        };
        
        // 清理临时rtId，确保我们的rtId不会重复
        if (this.form.rtId && this.form.rtId.toString().startsWith('temp_')) {
          delete submitData.rtVendor.rtId;
        }
        
        // 清理行数据中的临时ID，确保数据类型正确
        submitData.rtVendorLines = this.cleanTempIds(submitData.rtVendorLines);
        
        updateRtvendor(submitData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      })
    },
    // 关闭下拉列表
    closeSelect(){
      this.showItemSelect = false;
    },
    // 采购订单编号变化处理
    handlePoCodeChange(poCode) {
      if (poCode) {
        // 根据采购订单编号获取供应商和物料信息
        this.getPurchaseOrderInfo(poCode);
      } else {
        // 清空供应商信息
        this.form.vendorId = null;
        this.form.vendorCode = null;
        this.form.vendorName = null;
        this.form.vendorNick = null;
        // 清空物料列表
        this.materialList = [];
      }
    },
    // 获取采购订单列表
    getPurchaseOrderList(poCode) {
      // 设置加载状态
      this.purchaseOrderLoading = true;
      const params={

      }
      // 调用listPurchaseOrder接口获取采购订单数据
      return listPurchaseOrder(params).then(response => {
        if (response.code === 200) {
          // 更新组件的数据状态
          this.purchaseOrderData = response.rows || [];
          console.log(this.purchaseOrderData[0].vendorNick);
          this.form.vendorName=this.purchaseOrderData[0].vendorNick
          console.log(this.form.vendorNick);
          
          this.purchaseOrderTotal = response.total || 0;

          return response;
        } else {
          // 接口返回错误
          this.$message.error(response.msg || '获取采购订单列表失败');
          return Promise.reject(response);
        }
      }).catch(error => {
        // 接口调用失败
        console.error('获取采购订单列表失败:', error);
        this.$message.error('获取采购订单列表失败');
        return Promise.reject(error);
      }).finally(() => {
        // 无论成功失败都要关闭加载状态
        this.purchaseOrderLoading = false;
      });
    },

    // 获取采购订单信息
    getPurchaseOrderInfo(poCode) {
      // 从已确认的采购订单中查找
      const poInfo = this.rtCodeOptions.find(item => item.poCode === poCode);
      if (poInfo) {
        // 自动带出供应商信息
        this.form.vendorId = poInfo.vendorId;
        this.form.vendorCode = poInfo.vendorCode;
        this.form.vendorName = poInfo.vendorName;
        this.form.vendorNick = poInfo.vendorNick;
        this.getPurchaseOrderList(poCode)
        this.form.poId = poInfo.id;
        
        // 清除供应商字段的验证错误
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate('vendorName');
          }
        });
        
        // 获取采购订单物料明细
        this.getPurchaseOrderLines(poCode);
      }
    },
    // 获取采购订单物料明细
    getPurchaseOrderLines(poCode) {
      // 从已确认的采购订单中查找对应的ID
      const poInfo = this.rtCodeOptions.find(item => item.poCode === poCode);
      if (poInfo && poInfo.id) {
        // 调用API获取采购订单的物料明细
        detailPurchaseOrder(poInfo.id, {pageNum: 1, pageSize: 999}).then(response => {
          if (response.rows && response.rows.length > 0) {
            // 将物料明细数据设置到materialList中
            this.materialList = response.rows.map(item => ({
              lineId: 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
              rtId: this.form.rtId,
              itemId: item.itemId || item.id || item.productId,
              itemCode: item.itemCode || item.code || item.productCode,
              itemName: item.itemName || item.name || item.productName,
              specification: item.specification || item.spec || item.productSpc,
              unitOfMeasure: item.unitOfMeasure || item.unit || item.uom,
              quantityRted: item.quantity || item.orderQuantity || item.qty || 1,
              price: item.price || item.unitPrice || 0,
              totalPrice: 0, // 初始总价为0，后续计算
              priceExTax: 0, // 不含税单价，后续计算
              totalPriceExTax: 0, // 不含税总价，后续计算
              availableStock: item.availableStock || item.stockQuantity || 0, // 可用库存数量
              packageQuantity: item.packageQuantity || item.packageQty || 1, // 外包装数量
              batchCode: item.batchCode || '',
              warehouseId: null,
              warehouseName: '',
              locationId: null,
              locationName: '',
              areaId: null,
              areaName: '',
              discount: 1.0,
              taxRate: item.taxRate || 0.13,
              remark: ''
            }));
            this.$message.success(`成功加载 ${this.materialList.length} 条物料信息`);
            // 自动计算总价
            this.updateTotalPrice();
          } else {
            this.materialList = [];
            this.$message.warning('该采购订单暂无物料明细信息');
            // 清空总价
            this.form.totalPrice = 0;
            this.form.totalPriceExTax = 0;
          }
        }).catch(error => {
          console.error('获取采购订单物料明细失败:', error);
          this.$message.error('获取采购订单物料明细失败');
        });
      } else {
        this.$message.warning('未找到对应的采购订单信息');
      }
    },
    // 更新总价
    updateTotalPrice(totalPrice, totalPriceExTax) {
      this.form.totalPrice = totalPrice;
      this.form.totalPriceExTax = totalPriceExTax;
    },
    // 处理子组件行数据更新事件
    onLineDataUpdated(lineData) {
      // 可以在这里处理行数据更新后的逻辑
      console.log('行数据已更新:', lineData);
    },
    
    // 日期格式化工具函数 - 转换为后端期望的格式 "yyyy-MM-dd HH:mm:ss"
    formatDateForBackend(date) {
      if (!date) {
        const now = new Date();
        return now.getFullYear() + '-' + 
               String(now.getMonth() + 1).padStart(2, '0') + '-' + 
               String(now.getDate()).padStart(2, '0') + ' ' + 
               String(now.getHours()).padStart(2, '0') + ':' + 
               String(now.getMinutes()).padStart(2, '0') + ':' + 
               String(now.getSeconds()).padStart(2, '0');
      }
      
      if (typeof date === 'string' && date.includes('T')) {
        // 如果是ISO格式，转换为后端期望的格式
        const d = new Date(date);
        return d.getFullYear() + '-' + 
          String(d.getMonth() + 1).padStart(2, '0') + '-' + 
          String(d.getDate()).padStart(2, '0') + ' ' + 
          String(d.getHours()).padStart(2, '0') + ':' + 
          String(d.getMinutes()).padStart(2, '0') + ':' + 
          String(d.getSeconds()).padStart(2, '0');
      }
      
      return date;
    },
    
    // 清理行数据中的临时ID，确保数据类型正确，所有字段都不能为null
    cleanTempIds(rtVendorLines) {
      return rtVendorLines.map(line => {
        const cleanLine = { ...line };
        
        // 生成随机数字的函数,这里我是
        const generateRandomNumber = () => Math.floor(Math.random() * 1000000) + 1;
        const generateRandomString = () => 'RND_' + Math.random().toString(36).substr(2, 9);
        
        // 如果rtId是临时值，设置为随机数字
        if (cleanLine.rtId && cleanLine.rtId.toString().startsWith('temp_')) {
          cleanLine.rtId = generateRandomNumber();
        }
        // 如果lineId是临时值，设置为随机数字
        if (cleanLine.lineId && cleanLine.lineId.toString().startsWith('temp_')) {
          cleanLine.lineId = generateRandomNumber();
        }
        
        // 确保所有必需字段都有值，不能为null
        // ID字段
        cleanLine.itemId = cleanLine.itemId || generateRandomNumber();
        cleanLine.warehouseId = cleanLine.warehouseId || generateRandomNumber();
        cleanLine.locationId = cleanLine.locationId || generateRandomNumber();
        cleanLine.areaId = cleanLine.areaId || generateRandomNumber();
        cleanLine.materialStockId = cleanLine.materialStockId || generateRandomNumber();
        
        // 字符串字段
        cleanLine.itemCode = cleanLine.itemCode || generateRandomString();
        cleanLine.itemName = cleanLine.itemName || generateRandomString();
        cleanLine.specification = cleanLine.specification || generateRandomString();
        cleanLine.unitOfMeasure = cleanLine.unitOfMeasure || generateRandomString();
        cleanLine.batchCode = cleanLine.batchCode || generateRandomString();
        cleanLine.warehouseCode = cleanLine.warehouseCode || generateRandomString();
        cleanLine.warehouseName = cleanLine.warehouseName || generateRandomString();
        cleanLine.locationCode = cleanLine.locationCode || generateRandomString();
        cleanLine.locationName = cleanLine.locationName || generateRandomString();
        cleanLine.areaCode = cleanLine.areaCode || generateRandomString();
        cleanLine.areaName = cleanLine.areaName || generateRandomString();
        cleanLine.remark = cleanLine.remark || generateRandomString();
        cleanLine.currency = cleanLine.currency || 'CNY';
        cleanLine.gift = cleanLine.gift || 'N';
        cleanLine.bizUser = cleanLine.bizUser || 'system';
        cleanLine.createBy = cleanLine.createBy || 'system';
        cleanLine.updateBy = cleanLine.updateBy || 'system';
        cleanLine.searchValue = cleanLine.searchValue || '';
        
        // 数字字段
        cleanLine.quantityRted = cleanLine.quantityRted || 1;
        cleanLine.quantityBegin = cleanLine.quantityBegin || 0;
        cleanLine.quantityCurr = cleanLine.quantityCurr || 0;
        cleanLine.price = cleanLine.price || 0;
        cleanLine.priceExTax = cleanLine.priceExTax || 0;
        cleanLine.totalPrice = cleanLine.totalPrice || 0;
        cleanLine.totalPriceExTax = cleanLine.totalPriceExTax || 0;
        cleanLine.discount = cleanLine.discount || 1;
        cleanLine.exchRate = cleanLine.exchRate || 1;
        cleanLine.invoiceAmount = cleanLine.invoiceAmount || 0;
        cleanLine.attr1 = cleanLine.attr1 || 0;  // 确保attr1不为null
        cleanLine.attr2 = cleanLine.attr2 || 0;  // 确保attr2不为null
        cleanLine.attr3 = cleanLine.attr3 || 0;
        cleanLine.attr4 = cleanLine.attr4 || 0;
        cleanLine.userId = cleanLine.userId || 1;
        
        // 日期字段 - 使用后端期望的格式
        cleanLine.createTime = this.formatDateForBackend(cleanLine.createTime);
        cleanLine.updateTime = this.formatDateForBackend(cleanLine.updateTime);
        
        // 对象字段
        cleanLine.params = cleanLine.params || {};
        
        return cleanLine;
      });
    },
    
    // 清理主表单数据，确保所有字段都不为null
    cleanMainFormData(formData) {
      const cleanForm = { ...formData };
      
      // 生成随机数字的函数
      const generateRandomNumber = () => Math.floor(Math.random() * 1000000) + 1;
      const generateRandomString = () => 'RND_' + Math.random().toString(36).substr(2, 9);
      
      // 确保所有必需字段都有值，不能为null
      // ID字段
      cleanForm.rtId = cleanForm.rtId || generateRandomNumber();
      cleanForm.poId = cleanForm.poId || generateRandomNumber();
      cleanForm.vendorId = cleanForm.vendorId || generateRandomNumber();
      cleanForm.warehouseId = cleanForm.warehouseId || generateRandomNumber();
      cleanForm.userId = cleanForm.userId || generateRandomNumber();
      
      // 字符串字段
      cleanForm.rtCode = cleanForm.rtCode || generateRandomString();
      cleanForm.rtName = cleanForm.rtName || generateRandomString();
      cleanForm.poCode = cleanForm.poCode || generateRandomString();
      cleanForm.vendorCode = cleanForm.vendorCode || generateRandomString();
      cleanForm.vendorName = cleanForm.vendorName || generateRandomString();
      cleanForm.vendorNick = cleanForm.vendorNick || generateRandomString();
      cleanForm.batchCode = cleanForm.batchCode || generateRandomString();
      cleanForm.currency = cleanForm.currency || 'CNY';
      cleanForm.status = cleanForm.status || 'PREPARE';
      cleanForm.warehouseName = cleanForm.warehouseName || generateRandomString();
      cleanForm.remark = cleanForm.remark || generateRandomString();
      cleanForm.createBy = cleanForm.createBy || 'system';
      cleanForm.updateBy = cleanForm.updateBy || 'system';
      cleanForm.searchValue = cleanForm.searchValue || '';
      
      // 数字字段
      cleanForm.totalPrice = cleanForm.totalPrice || 0;
      cleanForm.totalPriceExTax = cleanForm.totalPriceExTax || 0;
      cleanForm.discount = cleanForm.discount || 1;
      
      // 日期字段 - 使用后端期望的格式
      cleanForm.rtDate = this.formatDateForBackend(cleanForm.rtDate);
      cleanForm.createTime = this.formatDateForBackend(cleanForm.createTime);
      cleanForm.updateTime = this.formatDateForBackend(cleanForm.updateTime);
      
      // 对象字段
      cleanForm.params = cleanForm.params || {};
      
      return cleanForm;
    },
    
    // 物料相关方法
    handleAddMaterial() {
      this.showItemSelect = true;
      this.$nextTick(() => {
        this.$refs.itemSelect.openDialog();
      });
    },
    
    handleDeleteMaterial(row) {
      const ids = row.lineId || this.selectedMaterialIds;
      if (Array.isArray(ids) && ids.length === 0) {
        this.$message.warning('请选择要删除的物料');
        return;
      }
      
      this.$confirm('确定要删除选中的物料吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (Array.isArray(ids)) {
          this.materialList = this.materialList.filter(item => !ids.includes(item.lineId));
        } else {
          this.materialList = this.materialList.filter(item => item.lineId !== ids);
        }
        this.$message.success('删除成功');
        this.updateTotalPrice();
      });
    },
    
    handleEditMaterial(row) {
      // 编辑物料信息
      this.showItemSelect = true;
      this.$nextTick(() => {
        this.$refs.itemSelect.openDialog();
      });
    },
    // 处理材料选择变更
    handleMaterialSelectionChange(selection) {
      this.selectedMaterialIds = selection.map(item => item.lineId);
    },
    
    // 处理数量变化
    handleQuantityChange(row) {
      // 重新计算该行的总价
      if (row.price && row.quantityRted) {
        row.totalPrice = Number(row.price) * Number(row.quantityRted);
        // 如果有税率，计算不含税价格
        if (row.taxRate) {
          row.priceExTax = Number(row.price) / (1 + Number(row.taxRate));
          row.totalPriceExTax = row.priceExTax * Number(row.quantityRted);
        }
      }
      // 更新总价
      this.updateTotalPrice();
    },
    
    // 处理价格变化
    handlePriceChange(row) {
      // 重新计算该行的总价
      if (row.price && row.quantityRted) {
        row.totalPrice = Number(row.price) * Number(row.quantityRted);
        // 如果有税率，计算不含税价格
        if (row.taxRate) {
          row.priceExTax = Number(row.price) / (1 + Number(row.taxRate));
          row.totalPriceExTax = row.priceExTax * Number(row.quantityRted);
        }
      }
      // 更新总价
      this.updateTotalPrice();
    },
    
    onItemSelected(selectedItems) {
      // 处理多个物料选择的情况
      if (Array.isArray(selectedItems) && selectedItems.length > 0) {
        // 过滤掉已经存在的物料（根据itemId判断）
        const existingItemIds = this.materialList.map(item => item.itemId);
        const newItems = selectedItems.filter(item => !existingItemIds.includes(item.itemId));
        
        if (newItems.length === 0) {
          this.$message.warning('所选物料已全部存在，未添加重复物料');
          this.closeItemSelect();
          return;
        }
        
        // 添加新的物料到列表
        newItems.forEach(item => {
          const newMaterial = {
            lineId: 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
            rtId: this.form.rtId,
            itemId: item.itemId,
            itemCode: item.itemCode,
            itemName: item.itemName,
            specification: item.specification,
            unitOfMeasure: item.unitOfMeasure,
            quantityRted: 1,
            price: 0,
            totalPrice: 0,
            priceExTax: 0, // 不含税单价
            totalPriceExTax: 0, // 不含税总价
            availableStock: item.availableStock || 0, // 可用库存数量
            packageQuantity: item.packageQuantity || 1, // 外包装数量
            batchCode: '',
            warehouseId: null,
            warehouseName: '',
            locationId: null,
            locationName: '',
            areaId: null,
            areaName: '',
            discount: 1.0,
            taxRate: 0.13,
            remark: ''
          };
          
          this.materialList.push(newMaterial);
        });
        
        this.$message.success(`成功添加 ${newItems.length} 个物料`);
        this.updateTotalPrice();
        this.closeItemSelect();
      } else if (selectedItems && selectedItems.itemId) {
        // 兼容单个物料选择的情况
        const newMaterial = {
          lineId: 'temp_' + Date.now(),
          rtId: this.form.rtId,
          itemId: selectedItems.itemId,
          itemCode: selectedItems.itemCode,
          itemName: selectedItems.itemName,
          specification: selectedItems.specification,
          unitOfMeasure: selectedItems.unitOfMeasure,
          quantityRted: 1,
          price: 0,
          totalPrice: 0,
          priceExTax: 0, // 不含税单价
          totalPriceExTax: 0, // 不含税总价
          availableStock: selectedItems.availableStock || 0, // 可用库存数量
          packageQuantity: selectedItems.packageQuantity || 1, // 外包装数量
          batchCode: '',
          warehouseId: null,
          warehouseName: '',
          locationId: null,
          locationName: '',
          areaId: null,
          areaName: '',
          discount: 1.0,
          taxRate: 0.13,
          remark: ''
        };
        
        this.materialList.push(newMaterial);
        this.$message.success('物料添加成功');
        this.updateTotalPrice();
        this.closeItemSelect();
      } else {
        this.$message.warning('未选择任何物料');
        this.closeItemSelect();
      }
    },
    // 关闭物料产品选择组件方法
    closeItemSelect() {
      this.showItemSelect = false;
    },
    // 计算总价的方法
    updateTotalPrice() {
      let totalPrice = 0;
      let totalPriceExTax = 0;
      
      this.materialList.forEach(item => {
        // 计算含税总价
        if (item.totalPrice) {
          totalPrice += Number(item.totalPrice);
        } else if (item.price && item.quantityRted) {
          // 如果没有总价，根据单价和数量计算
          const itemTotal = Number(item.price) * Number(item.quantityRted);
          totalPrice += itemTotal;
          item.totalPrice = itemTotal;
        }
        
        // 计算不含税总价
        if (item.priceExTax && item.quantityRted) {
          totalPriceExTax += Number(item.priceExTax) * Number(item.quantityRted);
        } else if (item.price && item.quantityRted && item.taxRate) {
          // 如果没有不含税价格，根据含税价格和税率计算
          const itemPriceExTax = Number(item.price) / (1 + Number(item.taxRate));
          const itemTotalExTax = itemPriceExTax * Number(item.quantityRted);
          totalPriceExTax += itemTotalExTax;
          item.priceExTax = itemPriceExTax;
          item.totalPriceExTax = itemTotalExTax;
        }
      });
      
      this.form.totalPrice = totalPrice;
      this.form.totalPriceExTax = totalPriceExTax;
    }
  }
}
</script>

<style lang="scss" scoped>
.mb8 {
  margin-bottom: 8px;
}

.box-card {
  margin-top: 10px;
}

.el-table {
  margin-top: 10px;
}
</style>
